/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_kit/zhiqim_git.htm
 *
 * ZhiqimGit is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.git;

import java.util.LinkedList;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * 压缩&解压对象缓存，由于调用次数较多，对其进行简单缓存
 *
 * @version v1.0.0 @author zouzhigang 2017-4-18 新建与整理
 */
public class GitZiper
{
    private static final int MAX = 7;
    private static final LinkedList<Inflater> inflaterList = new LinkedList<>();
    private static final LinkedList<Deflater> deflaterList = new LinkedList<>();

    /** 获取缓存中的一个实例，如果没有则创建 */
    public static Inflater inflater()
    {
        if (inflaterList.isEmpty())
            return new Inflater();
        
        synchronized (inflaterList)
        {//两次检查，第一次为提高效率，第二次为安全
            return inflaterList.isEmpty()?new Inflater():inflaterList.removeFirst();
        }
    }
    
    /** 获取缓存中的一个实例，如果没有则创建 */
    public static Deflater deflater(int level)
    {
        if (deflaterList.isEmpty())
            return new Deflater(level);
        
        synchronized (deflaterList)
        {//两次检查，第一次为提高效率，第二次为安全
            if (deflaterList.isEmpty())
                return new Deflater(level);
            
            Deflater instance = deflaterList.removeFirst();
            instance.setLevel(level);
            return instance;
        }
    }

    /** 关闭一个实例，如果缓存中已有MAX个，则真实关闭，否则重置并加到缓存 */
    public static void close(Inflater instance)
    {
        if (instance == null)
            return;
        
        if (inflaterList.size() >= MAX)
        {//只保留MAX个，超过的关闭
            instance.end();
            return;
        }
        
        instance.reset();
        synchronized (inflaterList)
        {//因为只在增加时同步，实际中允许超过MAX个
            inflaterList.addLast(instance);
        }
    }
    
    /** 关闭一个实例，如果缓存中已有MAX个，则真实关闭，否则重置并加到缓存 */
    public static void close(Deflater instance)
    {
        if (instance == null)
            return;
        
        if (deflaterList.size() >= MAX)
        {//只保留MAX个，超过的关闭
            instance.end();
            return;
        }
        
        instance.reset();
        synchronized (deflaterList)
        {//因为只在增加时同步，实际中允许超过MAX个
            deflaterList.addLast(instance);
        }
    }
}
